import LwtUtils from '../utils/LwtUtils.js'
import AuthProperties from '../properties/AtuhProperites.js'

/*
    简单写一下得了，没有实例去写完整的一套
*/

const includePath = [
    "/user/**"
]
const excludePath = [
    "/user/login", "/user/registry"
]


// 将路径提前正则表达式处理

for(let i in includePath) {
    includePath[i] = "^" + includePath[i].replace("**", "(.?)").replace(/\*$/, "(.*?)/").replace("*", "(.*?)").replace("/", "\/").replace("(.?)", "(.*?)")
}
for(let i in excludePath) {
    excludePath[i] = "^" + excludePath[i].replace("**", "(.?)").replace(/\*$/, "(.*?)/").replace("*", "(.*?)").replace("/", "\/").replace("(.?)", "(.*?)")
}

/*
    @ 拦截器
    @ 但是只有request是有用的

    @ 写的自己想笑，幽默拦截器
*/
export const preHandler = (request, response, handler) => {

    const url = String(request.url)
    // console.log("preHandler", request)
    for (let path of excludePath) {
        if (url.match(path)) {
            return true
        }
    }

    let isVerify = false
    for (let path of includePath) {
        if (url.match(path)) {
            isVerify = true // break不了，但是无伤大雅
            break
        }
    }
    
    if (!isVerify) {
        return true
    }
    // 鉴权
    if (!request.header || !request.header.token) {
        return false
    }
    
    const token = request.header.token
    try {
        LwtUtils.parser.setSignature(AuthProperties.lwtKey).parse(token)
    }catch(e) {
        // token鉴权失败
        return false
    }
    
    return true
}